<template>
  <van-field
    :label="titleText(options, item)"
    :name="item.itemTitle"
    :required="item.isRequired === 'Y'"
    :rules="[{ validator: validatorMessage }]"
    class="column"
    label-width="33rem"
  >
    <template #input>
      <p v-if="options.showDesc" class="desc f12 mb10">
        {{ options.description }}
      </p>
      <van-checkbox-group
        v-model="item.value"
        :disabled="type === 'view'"
        :max="options.multipleLimit || options.checkRange.max || 0"
        @change="onChange"
      >
        <template v-for="check in item.itemOptResList" :key="check.optionName">
          <template v-if="check.show || check.show === undefined">
            <van-checkbox :name="check.optionName" shape="square"
            >{{ check.optionName }}
            </van-checkbox>
            <input
              v-if="check?.isOther === 'Y'"
              v-model="check.otherValue"
              :disabled="type === 'view'"
              class="other_input"
            />
          </template>
        </template>
      </van-checkbox-group>
    </template>
  </van-field>
</template>

<script setup>

import { titleText } from "@/utils/common.js";

//defineOptions({ name: "H5Checkbox" });

const { item, type } = defineProps(["item", "type"]);
const emits = defineEmits(["change"]);
const { options } = JSON.parse(item.vformJson);
// 传递值改变后
const onChange = () => emits("change", item);
// 校验
const validatorMessage = (val) => {
  if (item.isRequired === "Y") {
    let length = item.value ? item.value.length : 0;
    if (length === 0) {
      return "请选择" + item.itemTitle;
    } else {
      if (options.checkRange?.min && length < options.checkRange?.min) {
        return `选项不能少于${options.checkRange.min}个`;
      }
      if (options.checkRange?.max && length > options.checkRange?.max) {
        return `选项不能大于${options.checkRange.max}个`;
      }
    }
  }
};
</script>
<style lang="less" scoped>
.column :deep(.van-field__control--custom) {
  flex-direction: column;
  align-items: self-start;

  .van-cell {
    padding: var(--van-cell-vertical-padding) 0;
  }
}

.other_input {
  border: 1px solid var(--van-gray-4);
  height: 3rem;
}

.van-checkbox {
  margin-bottom: 5px !important;
}
</style>